<template>
  <div class="dashboard_home_con">
    <div class="column_2">
      <Card title="博客访问情况" class="h400" :refresh="refresh">
        <el-radio-group size="small" class="radio_group" v-model="timeSection" @change="tabClick">
          <el-radio-button label="week">近一周</el-radio-button>
          <el-radio-button label="month">近一个月</el-radio-button>
          <el-radio-button label="year">近一年</el-radio-button>
        </el-radio-group>
        <div class="request_info_con">
          <div class="echarts_con" ref="request_charts_ref"></div>
          <div class="right_info_con">
            <p>今日访问次数</p>
            <span class="number">{{ this.requestData.today_request_count }}</span>

            <p>全部访问次数</p>
            <span class="number">{{ this.requestData.all_request }}</span>
          </div>
        </div>
      </Card>
    </div>

    <div class="column_2">
      <Card title="内存占有率" class="w50" :refresh="refresh">
        <div class="echarts_con_max">
          <div class="draw_canvas" ref="server_info_ref"></div>
        </div>
      </Card>
      <Card title="博客设置" :refresh="refresh" :refresh_enable="false">
        <div class="setting_con">
          <div class="line_con">
            <label for="primary_color">主体颜色:</label>
            <el-input size="mini color_input" v-model="prmiaryColor" @input="colorChange" id="primary_color"
              placeholder="主体颜色"></el-input>
            <el-color-picker class="color_block" @change="colorChange" v-model="prmiaryColor"></el-color-picker>
          </div>
          <div class="line_con">
            <el-tooltip class="item" effect="dark" :content="theme.deepColor.deep3_color" placement="top">
              <div class="kuai primary_deep3_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.deepColor.deep2_color" placement="top">
              <div class="kuai primary_deep2_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.deepColor.deep1_color" placement="top">
              <div class="kuai primary_deep1_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.primary_color" placement="top">
              <div class="kuai primary_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.thinColor.thin1_color" placement="top">
              <div class="kuai primary_thin1_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.thinColor.thin2_color" placement="top">
              <div class="kuai primary_thin2_color"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="theme.thinColor.thin3_color" placement="top">
              <div class="kuai primary_thin3_color"></div>
            </el-tooltip>
          </div>
          <div class="line_con">
            <label for="primary_color">公告内容:</label>
          </div>
          <div class="line_con">
            
            <el-input type="textarea" placeholder="公告内容" resize="none" v-model="notice_content" ></el-input>
          </div>
          <div class="line_con" style="display:flex;justify-content: flex-end;">
            <el-button type="primary" size="small" @click="updateNotice">发布公告</el-button>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>
<script>
import Card from "../components/Card.vue";
import { $request, $server, $updateTheme,$updateNotice } from '../../../api/admin'
import { $serverInfo } from "@/api/desk";
import { formatTime } from '../../../utils/tools'
import { Message } from "element-ui";

export default {
  name: "admin-dashboard",
  components: { Card },
  data() {
    return {
      notice_content: "", // 公告内容
      timeSection: "week",
      timer: null, // 计时器
      prmiaryColor: this.$store.state.theme.primary_color,
      serverEcharts: null, // 保存echarts对象 对应 服务信息项
      serverInfos: [], // 存服务器信息，最多只保留5条数据
      requestData: {} // 存请求记录的数据
    }
  },
  mounted() {
    this.getRequest()
    this.getServerInfo()
    this.getServerInfo()
    this.getNotice()
    this.timer = setInterval(() => {
      this.getServerInfo()
    }, 60000)
    this.$store.dispatch('setNowPath', this.$route)

  },
  destroyed() {
    clearInterval(this.timer)
  },
  computed: {
    theme: function () {
      return this.$store.state.theme
    }
  },
  methods: {
    // 提交公告内容
    submitNotice() {
      console.log("要提交的公告内容：", this.notice_content);
    },

    // 选项卡被点击
    tabClick() {
      this.getRequest()
    },

    // 获取公告内容
    getNotice(){
      $serverInfo().then(result=>{
        console.log("公告内容：",result);
        this.notice_content = result.data.announcement
      })
    },

    // 修改公告内容
    updateNotice(){
      $updateNotice({notice_content:this.notice_content}).then(()=>{
        Message.success("修改成功")
      }).catch(err=>{
        Message.error("修改失败"+err)
      })
    },

    // 色卡切换事件
    colorChange(e) {
      e = e || this.prmiaryColor
      this.$store.dispatch("setPrimary", e).then(() => {
        $updateTheme({
          key: "themeColor",
          val: e
        }).then(() => {
          Message.success("修改成功!")
        })
      }).catch(err => {
        Message.error("修改失败:" + err)
      })
    },

    // 卡牌刷新事件
    refresh(title) {
      switch (title) {
        case "博客访问情况":
          this.getRequest()
          break;
        case "内存占有率":
          this.getServerInfo()
          break;
        case "博客设置":

          break;
      }
    },

    // 获取请求数据
    getRequest() {
      $request({ type: this.timeSection }).then(result => {
        console.log("request: ", result);
        const data = this.requestData = result.data
        let request_charts = this.$echarts.init(this.$refs.request_charts_ref)
        let xIndexValue = []
        let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        let dayObj = {
          "week": 7,
          "month": 30,
          "year": 12
        }
        let startTime = new Date(data.start_time)
        startTime.setDate(startTime.getDate() + 1)
        // 开始计算对应x轴的下标
        for (let i = 0; i < dayObj[this.timeSection]; i++) {
          xIndexValue[i] = formatTime(startTime.getTime())
          if (this.timeSection === "year") {
            if (startTime.getMonth() === 11) {
              startTime.setDate(months[0] + 1)
            } else {
              startTime.setDate(months[startTime.getMonth()] + 1)
            }
          } else {
            startTime.setDate(startTime.getDate() + 1)
          }
        }
        // 设置options
        request_charts.setOption({
          xAxis: {
            type: 'category',
            data: xIndexValue
          },
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            top: 20,
            left: 60,
            width: "88%",
            height: "80%"
          },
          yAxis: {
            type: 'value',
            data: data.days
          },
          series: [
            {
              data: data.days.reverse(),
              type: 'line',
              smooth: true
            }
          ]
        })
      })
    },

    // 获取服务器信息
    getServerInfo() {
      $server().then(result => {
        console.log("服务器信息:", result);
        const data = result.data
        if (this.serverInfos.length === 5) {
          this.serverInfos = [...this.serverInfos.slice(1), data]
        } else {
          this.serverInfos.push(data)
        }
        let echarts
        if (!this.serverEcharts) {
          echarts = this.serverEcharts = this.$echarts.init(this.$refs.server_info_ref)
        } else {
          echarts = this.serverEcharts
        }

        let xIndexValue = []
        let yData = []
        this.serverInfos.forEach(item => {
          xIndexValue.push(formatTime(item.create_time))
          yData.push(item.freemem)
        })
        echarts.setOption({
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xIndexValue
          },
          yAxis: {
            type: 'value',
            max: data.totalmem,
            name: "内存信息",
            axisLabel: {
              formatter: function (value) {
                return (value / 1024 / 1024 / 1024).toFixed(2) + "G"
              }
            }
          },
          grid: {
            left: 50,
            top: 40,
            height: "70%"
          },
          series: [
            {
              data: yData,
              type: 'line',
              areaStyle: {}
            }
          ]
        })
      })
    }
  },
};
</script>
<style lang="scss" scoped>
.dashboard_home_con::-webkit-scrollbar {
  display: none;
}

.dashboard_home_con {
  width: 100%;
  height: 100%;
  padding-bottom: 5px;
  box-sizing: border-box;
  background-color: aliceblue;
  color: #00aaff;
  overflow-y: scroll;

  .nav_con {
    width: 100%;
    position: relative;
    padding: 20px 20px 0 20px;
    box-sizing: border-box;

    ._content {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      background-color: white;
      box-shadow: 0 0 20px 0 rgb(212, 212, 212);
      border-radius: 10px;
      position: relative;
    }
  }

  .w50 {
    max-width: 50%;
    min-width: 50%;
  }

  .column_2 {
    width: 100%;
    display: flex;

    .dashboard_card_con:nth-child(1) {
      margin: 20px 20px 0 20px;
    }

    .dashboard_card_con:nth-child(2) {
      margin: 20px 20px 0 0;
    }

    .setting_con {
      width: 100%;
      height: 100%;
      padding: 0 10px;
      box-sizing: border-box;

      label {
        color: #333;
        margin-right: 10px;
      }

      .line_con {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;

        .kuai {
          width: 30px;
          height: 30px;
          margin: 1px;
          display: inline-block;
        }

        p {
          color: #444;
          font-size: 12px;
          padding: 5px 0;
        }
      }

      .color_input {
        width: 50%;
      }

      .color_block {
        margin-left: 10px;
        border-radius: 3px;
      }

      .color_block:hover {
        cursor: pointer;
      }
    }

    .echarts_con_max {
      width: 100%;
      height: 100%;
      display: flex;

      .draw_canvas {
        width: 100%;
        height: 100%;
      }
    }

    .request_info_con {
      width: 100%;
      flex: 1 auto;
      // border: 1px solid red;
      display: flex;

      .echarts_con {
        width: 80%;
        height: 210px;
      }

      .right_info_con {
        border: 1px solid rgb(236, 236, 236);
        flex: 1 auto;
        border-radius: 10px;
        font-size: 15px;
        padding: 10px;
        box-sizing: border-box;

        p {
          font-size: 13px;
          color: #555;
          margin-bottom: 2px;
        }

        span {
          color: white;
          font-size: 15px;
          background-color: #00a9ff;
          padding: 0px 10px;
          border-radius: 3px;
          box-sizing: border-box;
          display: inline-block;
          margin-bottom: 20px;
        }
      }
    }
  }
}
</style>